﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ARPAMIS.Presentation.Web.Models.ViewModels;
using Dm.Domain.CrossCutting;
using Dm.Domain.Entities;
using Dm.Domain.Business;



namespace ARPAMIS.Presentation.Web.Controllers
{
    public class StudentController : Controller
    {

        private const int _queryStringSuccessSaveKey = 1;
        private const int _queryStringSuccessUpdateKey = 2;
        private const int _queryStringSuccessDeleteKey = 3;

        private StudentBusiness _studentBusiness;

        public StudentController()
        {
            _studentBusiness = new StudentBusiness();
        }

        public ActionResult Index(int? id)
        {
            RegisterStudentViewModel viewModel;

            if (id.HasValue)
            {
                viewModel = new RegisterStudentViewModel(id.Value);
            }
            else
            {
                viewModel = new RegisterStudentViewModel();
            }

            return View();
        }

        public ActionResult Register(int? id)
        {
            RegisterStudentViewModel viewModel;
            if (id.HasValue)
            {
                viewModel = new RegisterStudentViewModel(id.Value);
                viewModel.Mode = Settings.DataManipulationMode.Edit;
            }
            else
            {
                viewModel = new RegisterStudentViewModel();
                viewModel.Mode = Settings.DataManipulationMode.Create;
            }
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Register(RegisterStudentViewModel viewModel, string action)
        {
            if (action == "Save")
            {
                if (ModelState.IsValid)
                {
                    if (viewModel.Mode == Settings.DataManipulationMode.Create)
                    {
                        Student newStudent = new Student();
                        newStudent.FirstName = viewModel.FirstName;
                        newStudent.MiddleName = viewModel.MiddleName;
                        newStudent.LastName = viewModel.LastName;
                        newStudent.ControlNumber = viewModel.StudentNumber;
                        newStudent.Address = new Address { AddressLine1 = viewModel.Address };
                        newStudent.ContactNumber = viewModel.ContactNumber;
                        newStudent.YearLevel = viewModel.YearLevel;
                        newStudent.StartDate = viewModel.DateAttended;
                        newStudent.EndDate = viewModel.DateGraduated;
                        newStudent.StatusId = Settings.Statuses.ActiveStatus;
                        _studentBusiness.Create(newStudent);

                        return RedirectToAction("List", new { status = _queryStringSuccessSaveKey });
                    }
                    else if (viewModel.Mode == Settings.DataManipulationMode.Edit)
                    {
                        Student existingStudent = _studentBusiness.Retrieve(viewModel.StudentId);
                        existingStudent.FirstName = viewModel.FirstName;
                        existingStudent.MiddleName = viewModel.MiddleName;
                        existingStudent.LastName = viewModel.LastName;
                        existingStudent.ControlNumber = viewModel.StudentNumber;
                        existingStudent.Address.AddressLine1 = viewModel.Address;
                        existingStudent.ContactNumber = viewModel.ContactNumber;
                        existingStudent.YearLevel = viewModel.YearLevel;
                        existingStudent.StartDate = viewModel.DateAttended;
                        existingStudent.EndDate = viewModel.DateGraduated;
                        _studentBusiness.Update(existingStudent);

                        return RedirectToAction("List", new { status = _queryStringSuccessUpdateKey });
                    }
                }
            }
            else if (action == "Deactivate")
            {
                Student studentToDelete = _studentBusiness.Retrieve(viewModel.StudentId);
                studentToDelete.StatusId = Settings.Statuses.InactiveStatus;
                _studentBusiness.Update(studentToDelete);
                return RedirectToAction("List", new { status = _queryStringSuccessDeleteKey });
            }
            return View(viewModel);
        }


        public ActionResult List(int? status)
        {
            ListStudentViewModel viewModel = new ListStudentViewModel();

            if (status.HasValue)
            {
                if (status == _queryStringSuccessSaveKey) { viewModel.Message = Settings.Messages<Student>.SAVE_SUCCESS_MESSAGE; }
                if (status == _queryStringSuccessUpdateKey) { viewModel.Message = Settings.Messages<Student>.UPDATE_SUCCESS_MESSAGE; }
                if (status == _queryStringSuccessDeleteKey) { viewModel.Message = Settings.Messages<Student>.DELETE_SUCCESS_MESSAGE; }
            }

            viewModel.Students = _studentBusiness.RetrieveAll();
            return View(viewModel);
        }

        public JsonResult GetStudentList(int page, int rows, string firstName, string middleName, string lastName, string sidx, string sord)
        {
            int totalRows = 0;
            var students = _studentBusiness.PagedSearch(page,rows,firstName,middleName,lastName,sidx,sord, out totalRows);
            var obj = new List<object>();
            students.ForEach(s => obj.Add(new
            {
                StudentNumber = s.ControlNumber,
                StudentId = s.EntityId,
                FirstName = s.FirstName,
                MiddleName = s.MiddleName,
                LastName = s.LastName,
                link = "<a href='" + Url.Content("~/Student/Register/" + s.EntityId) + "'>View</a>"
            }));

            var JsonToReturn = new
                {
                    total = Math.Ceiling((decimal)totalRows / rows),
                    page = page,
                    records = obj.Count,
                    rows = obj
                };

            return Json(JsonToReturn, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult List(ListStudentViewModel viewModel, string action)
        {
            if (action == "Search")
            {
                viewModel.Students = _studentBusiness.Search(
                    viewModel.FirstName,
                    viewModel.MiddleName,
                    viewModel.LastName,
                    viewModel.StudentNumber,
                    viewModel.Email,
                    viewModel.ContactNumber,
                    viewModel.Address);
            }
            else if (action == "Add")
            {
                return RedirectToAction("Register");
            }
            return View(viewModel);
        }

    }
}
